package kt.com.bilin.coin.common

import android.app.Activity
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import android.os.Bundle
import android.os.Environment
import android.os.Parcelable
import android.view.View
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import com.alibaba.android.arouter.facade.Postcard
import com.alibaba.android.arouter.launcher.ARouter
import com.baidu.idl.face.platform.utils.FileUtils
import com.baidu.idl.face.platform.utils.IoUtils
import com.bilin.coin.ApiConstant
import com.bilin.coin.App
import com.kingja.loadsir.callback.SuccessCallback
import com.kingja.loadsir.core.LoadService
import com.tencent.smtt.sdk.QbSdk
import kt.com.bilin.coin.helper.loadsir.EmptyCallback
import kt.com.bilin.coin.helper.loadsir.LoadingCallback
import kt.com.bilin.coin.utils.Logger
import java.io.File
import java.io.Serializable
import java.text.DecimalFormat
import java.text.SimpleDateFormat
import java.util.*
import kotlin.collections.HashMap

fun CharSequence?.clipboard(successText: String = "复制成功") {
    if (this == null) return
    try {
        val cm = App.getApp().getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
        val mClipData = ClipData.newPlainText("Label", this)
        cm.setPrimaryClip(mClipData)
        toastMessageLong(successText)
    } catch (e: Exception) {
        Logger.e(e)
    }
}

fun Context?.goActicity(clazz: Class<*>?, bundle: Bundle? = null, requestCode: Int? = null) {
    if (this == null || clazz == null) return
    val intent = Intent(this, clazz)
    if (bundle != null)
        intent.putExtras(bundle)
    if (requestCode != null && this is Activity) {
        startActivityForResult(intent, requestCode)
    } else {
        startActivity(intent)
    }
}

fun Context?.goActicityFinish(clazz: Class<*>, bundle: Bundle? = null, requestCode: Int? = null) {
    goActicity(clazz, bundle, requestCode)
    if (this is Activity)
        finish()
}

fun View.visible() = apply { visibility = View.VISIBLE }
fun View.gone() = apply { visibility = View.GONE }
fun View.invisible() = apply { visibility = View.INVISIBLE }
fun <T> LoadService<T>.showEmptyCallback() = showCallback(EmptyCallback::class.java)
fun <T> LoadService<T>.showLoadingCallback() = showCallback(LoadingCallback::class.java)
fun <T> LoadService<T>.showLoadingBeforeSuccessCallback() {
    if (currentCallback != SuccessCallback::class.java) showCallback(LoadingCallback::class.java)
}

fun CharSequence?.toastMessageLong() = this?.let {
    toastMessageLong(toString())
}

fun ARouterNavigation(path: String, postcard: (Postcard.() -> Unit)? = null) {
    if (postcard != null) {
        ARouter.getInstance().build(path).also(postcard).navigation()
    } else {
        ARouter.getInstance().build(path).navigation()
    }
}

fun openUrl(url: String, title: String) {
    ARouterNavigation("/common/WebPageLoading") {
        withString("url", url)
        withString("title", title)
    }
}

fun Activity.showAssetsFile(fileName: String, title: String) {
    val file = File(cacheDir, fileName)
    if (!file.exists()) {
        IoUtils.copyStream(assets.open(fileName), file)
    }
    QbSdk.openFileReader(this, file.path, null) {
        Logger.e("openFileReader==>$it")
    }
}

fun Activity.ARouterNavigation(path: String, requestCode: Int? = null, postcard: (Postcard.() -> Unit)? = null) {
    if (postcard != null) {
        ARouter.getInstance().build(path).also(postcard).let {
            if (requestCode != null) {
                it.navigation(this, requestCode)
            } else {
                it.navigation(this)
            }
        }
    } else {
        ARouter.getInstance().build(path).navigation(this)
    }
}

fun Int.toastMessageLong() = toastMessageLong(getString())
fun Int.toColor() = ContextCompat.getColor(App.getApp(), this)
fun Int.getDrawable() = ContextCompat.getDrawable(App.getApp(), this)
fun Int.getString() = getString(this)
fun Int?.dp2px() = this?.let { dp2px(this) } ?: 0
fun Double?.format() = this?.let { DecimalFormat("0.##").format(this) } ?: ""
fun String?.formatDouble() = try {
    this?.let { DecimalFormat("0.##").format(it.toDouble()) } ?: this
} catch (e: Throwable) {
    this
}

fun Date.toYYYYMMDD() = SimpleDateFormat("yyyy-MM-dd").format(this)
val String.appendOSSURL get() = if (startsWith("http")) this else ApiConstant.OSSURL + this
fun Context.checkAppInstalled(pkgName: String?): Boolean {
    if (pkgName == null || pkgName.isEmpty()) {
        return false
    }
    var packageInfo: PackageInfo?
    try {
        packageInfo = packageManager.getPackageInfo(pkgName, 0)
    } catch (e: PackageManager.NameNotFoundException) {
        packageInfo = null
        e.printStackTrace()
    }
    return packageInfo != null
}

fun Context.startAPP(appPackageName: String?): Boolean {
    return try {
        val intent = packageManager.getLaunchIntentForPackage(appPackageName!!)
        startActivity(intent)
        true
    } catch (e: Exception) {
        //Toast.makeText(context, "请先安装app", Toast.LENGTH_LONG).show();
        false
    }
}

fun Context.getAppRootPath(): File {
    return if (sdCardIsAvailable()) {
        Environment.getExternalStorageDirectory()
    } else {
        filesDir
    }
}

fun sdCardIsAvailable(): Boolean {
    return if (Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED) {
        Environment.getExternalStorageDirectory().canWrite()
    } else false
}

inline fun <reified T : Fragment> Fragment.put(pair: Pair<String, Any>): T {
    if (arguments == null) {
        arguments = Bundle()
    }
    arguments?.run {
        val name = pair.first
        when (val value = pair.second) {
            is Int -> putInt(name, value)
            is Byte -> putByte(name, value)
            is Char -> putChar(name, value)
            is Short -> putShort(name, value)
            is Boolean -> putBoolean(name, value)
            is Long -> putLong(name, value)
            is Float -> putFloat(name, value)
            is Double -> putDouble(name, value)
            is String -> putString(name, value)
            is CharSequence -> putCharSequence(name, value)
            is Parcelable -> putParcelable(name, value)
            is Array<*> -> putSerializable(name, value)
            is ArrayList<*> -> putSerializable(name, value)
            is Serializable -> putSerializable(name, value)
            is BooleanArray -> putBooleanArray(name, value)
            is ByteArray -> putByteArray(name, value)
            is ShortArray -> putShortArray(name, value)
            is CharArray -> putCharArray(name, value)
            is IntArray -> putIntArray(name, value)
            is LongArray -> putLongArray(name, value)
            is FloatArray -> putFloatArray(name, value)
            is DoubleArray -> putDoubleArray(name, value)
            is Bundle -> putBundle(name, value)
            else -> {
            }
        }
    }
    return this as T
}